package sv.com.seguros.dso.asg;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import sv.com.seguros.dso.BaseServiceImpl;
import sv.com.seguros.dto.asg.AsgVenta;
import sv.com.seguros.exception.WebException;
import sv.com.seguros.web.util.WebUtilidades;

public class AsgVentaServiceImpl extends BaseServiceImpl implements AsgVentaService {
	
	@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = {Exception.class, WebException.class})
	public void save(AsgVenta asgVenta) throws WebException{
		try{
			asgVenta.setAsgVentaNumero("0");
			super.save(asgVenta);
			asgVenta.setAsgVentaNumero(StringUtils.leftPad(asgVenta.getAsgVentaId().toString(), 8, "0"));
			super.update(asgVenta);
		}catch(Exception e){
			logger.error("Exception:", e);
			throw new WebException("Problemas al tratar de guardar la informaci\u00F3n");
		}
	}
	
	@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = {Exception.class, WebException.class})
	public void finalizar(Long asgVentaId) throws WebException{
		try{
			String hqlQuery = "update AsgVenta set asgVentaFinalizado = '1', asgVentaFechaFinalizacion = :fecha where asgVentaId = :asgVentaId";
			Map<String, Object> parameters = new HashMap<String, Object>();
			parameters.put("fecha", WebUtilidades.dateFormatAsYYYYMMDD.format(new Date()));
			parameters.put("asgVentaId", asgVentaId);
			executeNonHibernateQuery(hqlQuery, parameters);
		}catch(Exception e){
			logger.error("Exception:", e);
			throw new WebException("Problemas al tratar de actualizar informaci\u00F3n del reclamo");
		}
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = false, rollbackFor = {Exception.class, WebException.class})
	public void deleteAsgVenta(Long asgVentaId) throws Exception{
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("asgVentaId", asgVentaId);
		String hqlQuery = "delete from AsgSeguimiento where asgVenta.asgVentaId = :asgVentaId)";
		executeNonHibernateQuery(hqlQuery, parameters);
		hqlQuery = "delete from AsgContacto where asgVenta.asgVentaId = :asgVentaId)";
		executeNonHibernateQuery(hqlQuery, parameters);
		hqlQuery = "delete from AsgVenta where asgVentaId = :asgVentaId";
		executeNonHibernateQuery(hqlQuery, parameters);
	}
}
